package com.boarsoft.boar.server.biz;

import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.boarsoft.boar.entity.AppInfo;
import com.boarsoft.boar.entity.AppInst;
import com.boarsoft.boar.entity.ServerInfo;
import com.boarsoft.boar.server.ServerBiz;
import com.boarsoft.boar.server.ServerInstBiz;
import com.boarsoft.hibernate.biz.SimpleBizImpl;

@Component("serverInstBiz")
public class ServerInstBizImpl extends SimpleBizImpl implements ServerInstBiz {
	@Autowired
	protected ServerBiz serverBiz;
	
	@Override
	@Transactional
	public void add(String[] appIds, String serverId) {
		String hql = new StringBuilder("select o from ").append(AppInst.class.getName())
				.append(" o where o.serverId=? and o.appId=? and o.port=?").toString();
		Query<AppInst> q = dao.createQuery(AppInst.class, hql);
		q.setParameter(0, serverId); //
		ServerInfo s = serverBiz.get(serverId);
		for (String appId : appIds) {
			AppInfo a = dao.get(AppInfo.class, appId);
			q.setParameter(1, appId);
			q.setParameter(2, a.getPort());
			AppInst o = null;
			o = (AppInst) q.uniqueResult();
			if (o == null) {
				o = new AppInst();
				o.setAppId(appId);
				o.setServerId(serverId);
				o.setPort(a.getPort());
				dao.save(o);
			}
			o.setIp(s.getIp());
			o.setEnv(s.getEnv());
			o.setDeployPath(a.getDeployPath());
			o.setTempPath(a.getTempPath());
			o.setUser(a.getUser());
		}
	}
}